package com.bdsys.daoimpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.bdsys.common.dao.BasicDaoAbstract;
import com.bdsys.dao.DeviceDAO;
import com.bdsys.domain.DeviceDomain;

public class DeviceDAOImpl extends BasicDaoAbstract implements DeviceDAO{

	public DeviceDAOImpl(){
		super("device");
	}
	
	@Override
	public void addDevice(DeviceDomain inDomain) {
		getJdbcTemplate().update(getSql(DEVICE_INSERT),
				new Object[] { inDomain.getDid(), inDomain.getDname(),
				inDomain.getDstatus(), inDomain.getClassification() });
	}

	@Override
	public List<DeviceDomain> selectAll() {
		List<Map<String, Object>> list =  getJdbcTemplate().queryForList(getSql(DEVICE_SEARCH_ALL), new Object[]{});
		
		List<DeviceDomain> outDomainList = new ArrayList<DeviceDomain>();
		
		for(Map<String, Object> map : list){
			DeviceDomain outDomain = new DeviceDomain();
			outDomain.setDid(map.get("did").toString());
			outDomain.setDname(map.get("dname").toString());
			outDomain.setDstatus(map.get("dstatus").toString());
			outDomain.setClassification(map.get("classification").toString());
			outDomainList.add(outDomain);
		}
		
		return outDomainList;
	}

	@Override
	public List<DeviceDomain> selectByConditions(DeviceDomain deviceDo) {
		StringBuilder sb = new StringBuilder(getSql(DEVICE_SEARCH_ALL));
		List<String> list = new ArrayList<String>();
		boolean isWhere = false;
		if((deviceDo.getDid() != null && !deviceDo.getDid().isEmpty())){
			sb.append(" where did = ?");
			isWhere = true;
			list.add(deviceDo.getDid());
		}
		
		if ((deviceDo.getDname() != null && !deviceDo.getDname().isEmpty())){
			if(isWhere){
				sb.append(" and dname = ?");
			}else {
				sb.append(" where dname = ?");
				
				isWhere = true;
			}
			
			list.add(deviceDo.getDname());
		}
		
		if ((deviceDo.getDstatus() != null && !deviceDo.getDstatus().isEmpty())){
			if(isWhere){
				sb.append(" and dstatus = ?");
			}else {
				sb.append(" where dstatus = ?");
				
				isWhere = true;
			}
			
			list.add(deviceDo.getDstatus());
		}
		
		if ((deviceDo.getClassification() != null && !deviceDo.getClassification().isEmpty())){
			if(isWhere){
				sb.append(" and classification = ?");
			}else {
				sb.append(" where classification = ?");
			}
			
			list.add(deviceDo.getClassification());
		}
		
		List<Map<String, Object>> resultList =  getJdbcTemplate().queryForList(sb.toString(), list.toArray());
		List<DeviceDomain> outDomainList = new ArrayList<DeviceDomain>();
		for(Map<String, Object> map : resultList){
			DeviceDomain outDomain = new DeviceDomain();
			outDomain.setDid(map.get("did").toString());
			outDomain.setDname(map.get("dname").toString());
			outDomain.setDstatus(map.get("dstatus").toString());
			outDomain.setClassification(map.get("classification").toString());
			outDomainList.add(outDomain);
		}
		
		return outDomainList;
	}
}
